<template>
  <div class="jeecg-resizer" :style="getWrapStyleRef" @mousedown="onMouseDown"></div>
</template>
<script lang="ts">
  import { computed, defineComponent, reactive, ref, unref } from 'vue';
  import { useEventListener } from '/@/hooks/event/useEventListener';

  export default defineComponent({
    name: 'JeecgResizer',
    props: {
      position: {
        type: String as PropType<'left' | 'right' | 'top' | 'bottom'>,
        default: 'left',
      },
    },
    emits: ['move', 'update:collapsed'],
    setup(props, { emit }) {
      const isCollapsed = ref<Boolean>(false);
      const drift = reactive({
        lastX: 0,
        lastY: 0,
      });

      const getWrapStyleRef = computed(() => {
        if (props.position === 'top' || props.position === 'bottom') {
          return { height: '18px', cursor: 's-resize' };
        } else {
          return { width: '18px', cursor: 'w-resize' };
        }
      });

      useEventListener({
        el: document,
        name: 'mouseup',
        listener: onMouseUp,
        wait: 0,
      });

      function onMouseDown(event) {
        isCollapsed.value = true;
        drift.lastX = event.screenX;
        drift.lastY = event.screenY;
        document.addEventListener('mousemove', onMouseMove);
      }

      function onMouseMove(event) {
        if (isCollapsed.value) {
          emit('move', event, event.screenX - drift.lastX, event.screenY - drift.lastY);
          drift.lastX = event.screenX;
          drift.lastY = event.screenY;
        }
      }

      function onMouseUp() {
        document.removeEventListener('mousemove', onMouseMove);
        drift.lastX = 0;
        drift.lastY = 0;
        isCollapsed.value = false;
      }

      return {
        getWrapStyleRef,
        ...unref(props),
        onMouseDown,
      };
    },
  });
</script>
<style lang="less">
  .jeecg-resizer {
    z-index: 1006;
    background: #fff;
    user-select: none;
  }
</style>
